package cn.szzsi.business.interceptor;

/**
 * Created by haotian on 2016/12/8.
 */

import cn.szzsi.common.util.CommonUtil;
import cn.szzsi.common.util.HttpExtKit;
import cn.szzsi.common.util.IdGen;
import cn.szzsi.common.util.SystemConfigUtil;
import cn.szzsi.model.*;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import javax.servlet.http.Cookie;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class WechatLoginInterceptor implements Interceptor {
    private String appid;//微信应用id
    private String secret;//微信应用秘钥

    public void intercept(Invocation ai) {
        Controller c = ai.getController();
        String shopId=c.getPara("shopId");
        SiteConfig siteConfig = SiteConfig.dao.findByShopId(shopId);
        if(isNeedWechatLogin(c,siteConfig)){
            if (!weixinLogin(c, siteConfig)) {
                //获取code并且未登录成功时,中断当前操作流程
                return;
            }
        }
        ai.invoke();
    }

    /**
     * 是否需要微信登录的判断条件：
     * 1、微信浏览器
     * 2、用户session不存在
     * 3、系统配置中开启微信登录授权
     * @param c
     * @param siteConfig
     * @return
     */
    public boolean isNeedWechatLogin(Controller c,SiteConfig siteConfig){
        boolean flag = false;
        if(CommonUtil.isWeixinBrowser(c)){//是否微信浏览器
            c.setAttr(CommonUtil.BROWSER_TYPE,"weixinBrowser");
            String loginMemberId = c.getSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME);//获取当前登录用户
            if(StrKit.isBlank(loginMemberId)){
                int openWeixnLogin=siteConfig.getInt("openWeixnLogin");
                if (openWeixnLogin==1) {
                    flag = true;
                }
            }
        }
        return flag;
    }

    /**
     * 微信登录
     * 1，获取code之前
     * 2，获取code之后
     * @param c
     * @param siteConfig
     * @return
     */
    private boolean weixinLogin(Controller c,SiteConfig siteConfig){
        boolean flag = false;
        String code =c.getPara("code");
        Cookie loginMemberUsernameCookie;
        int openWeixnLogin=siteConfig.getInt("openWeixnLogin");
        if (openWeixnLogin==1) {//开启微信授权登录
            appid=siteConfig.getStr("appid");
            secret=siteConfig.getStr("secret");
            if(StrKit.isBlank(code)){//code为null
                String fansIndexUrl= CommonUtil.getBackUrl(c);
                String redirect_uri= null;
                try {
                    redirect_uri = URLEncoder.encode(fansIndexUrl,"utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String reqUrl="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                c.redirect(reqUrl);
            }else{
                //已经获取到code,根据code取access_token
                String reqUrl="https://api.weixin.qq.com/sns/oauth2/access_token?APPID="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
                String result= HttpExtKit.sendPost(reqUrl,"","");
                if(StrKit.notBlank(result)) {
                    JSONObject obj = new JSONObject(result);
                    if (obj.get("access_token") != null) {
                        String access_token = obj.get("access_token").toString();
                        String openid = obj.get("openid").toString();
                        Member member = Member.dao.isExistByOpenid(openid);
                        if (member != null) {//用户名已存在,将用户的id存入session,并且存入cookie
                            c.setAttr("loginMember", member);
                            // 写入会员登录Session
                            c.setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, member.getStr("id"));
                            // 写入会员登录Cookie
                            loginMemberUsernameCookie = null;
                            Cookie loginTypeCookie = null;
                            try {
                                loginMemberUsernameCookie = new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, URLEncoder.encode(member.getStr("username").toLowerCase(), "UTF-8"));
                                loginTypeCookie = new Cookie(Member.LOGIN_TYPE_COOKIE_NAME, "customer");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            loginMemberUsernameCookie.setPath(c.getRequest().getContextPath() + "/");
                            loginTypeCookie.setPath(c.getRequest().getContextPath() + "/");
                            c.getResponse().addCookie(loginMemberUsernameCookie);
                            c.getResponse().addCookie(loginTypeCookie);

                        } else {//用户名未存在
                            //拉取用户信息
                            String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
                            String resultUserInfo = HttpExtKit.sendGet(getUserInfo, "");
                            JSONObject userJson = new JSONObject(resultUserInfo);
                            String nickname = userJson.get("nickname").toString();
                            String sex = userJson.get("sex").toString();
                            String country = userJson.get("country").toString();
                            String province = userJson.get("province").toString();
                            String city = userJson.get("city").toString();
                            String headimgurl = userJson.get("headimgurl").toString();
                            String privilege = userJson.get("privilege").toString();
                            //String unionid=userJson.get("unionid").toString();//待处理
                            String registerIp = c.getRequest().getRemoteAddr();
                            //保存用户信息
                            member = Member.saveMemberInfo("0", "0", openid, nickname, sex, country, province, city, headimgurl, privilege, null, siteConfig.getUid(), registerIp, IdGen.get().nextId(10));

                            Member saveMember = Member.dao.getByOpenid(openid);//上一步保存的信息会员
                            c.setAttr("loginMember", saveMember);
                            // 写入会员登录Session
                            c.setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, saveMember.getStr("id"));
                            // 写入会员登录Cookie
                            loginMemberUsernameCookie = null;
                            Cookie loginTypeCookie = null;
                            try {
                                loginMemberUsernameCookie = new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, URLEncoder.encode(saveMember.getStr("username").toLowerCase(), "UTF-8"));
                                loginTypeCookie = new Cookie(Member.LOGIN_TYPE_COOKIE_NAME, "customer");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            loginMemberUsernameCookie.setPath(c.getRequest().getContextPath() + "/");
                            loginTypeCookie.setPath(c.getRequest().getContextPath() + "/");
                            c.getResponse().addCookie(loginMemberUsernameCookie);
                            c.getResponse().addCookie(loginTypeCookie);
                        }
                        flag = true;
                    }
                }
            }
        }
        return flag;
    }
}
